<!--
 * @Description:
 * @Version: 1.0
 * @Autor: haozhuang
 * @Date: 2020-05-07 10:32:05
 * @LastEditors: haozhuang
 * @LastEditTime: 2020-05-08 17:09:05
 -->
<template>
  <div id="priject" class="el-row--flex" :class="{ active: isShow }">
    <div class="el-row--flex left ">
      <folderTree ref="folderTree" @selectedFolder="selectedFolder"/>
      <div v-if="!fileListIsHide" class="content el-row--flex">
        <el-input
          v-model="searchInput"
          placeholder="请输入内容"
          class="input-with-select search"
          @keyup.enter.native="selectedFolder"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="selectedFolder"
          />
        </el-input>

        <el-scrollbar>
          <div class="list">
            <draggable :list="fileList.fileInfos"
                       @end="end"
                       :options="{animation: 300}"
            >
              <dl
                v-for="(item, index) in fileList.fileInfos"
                :key="index"
                :class="{ active: item.isActive }"
                @click="selected(item)"
                draggable
                @contextmenu.prevent="contextmenu($event, item)"
              >
                <dt class="ellipsis">
                  {{ item.name.replace("." + item.suffix, "") }}
                </dt>
                <dd>{{ item.updateTime }}</dd>
                <dd>创建人：{{ item.creater }}</dd>
                <dd>编辑人：{{ item.editor }}</dd>
                <img
                  v-if="item.suffix == 'json'"
                  src="@/assets/project/mind.png"
                  alt=""
                >
                <img
                  v-if="item.suffix == 'html' || item.suffix == 'docx'"
                  src="@/assets/project/doc.png"
                  alt=""
                >
                <img
                  v-if="item.suffix == 'jpg' || item.suffix == 'png'"
                  src="@/assets/project/image.png"
                  alt=""
                >
                <img
                  v-if="item.suffix == 'pdf'"
                  src="@/assets/project/pdf.png"
                  alt=""
                >
              </dl>
            </draggable>
          </div>
        </el-scrollbar>
      </div>
      <img src="~@/assets/project/arrow.png" class="arrow" alt="" @click="isShow = !isShow">
    </div>

    <cont ref="cont"/>
    <fileShare :file-share-data="fileShareData" @colseDialog="colseDialog"/>
    <v-contextmenu ref="contextmenu">
      <v-contextmenu-item @click="open('update')">
        <img src="~@/assets/edit.png" width="10" alt="" style="margin-right:8px">重命名
      </v-contextmenu-item>
      <v-contextmenu-item @click="deleteFile">
        <img src="~@/assets/delete.png" width="10" alt="" style="margin-right:8px">删除
      </v-contextmenu-item>
      <v-contextmenu-item @click="share">
        <img src="~@/assets/share.png" width="10" alt="" style="margin-right:8px">分享
      </v-contextmenu-item>
      <v-contextmenu-item
        v-if="contextmenuData && contextmenuData.suffix.includes('html')"
        @click="download"
      >
        <img src="~@/assets/export.png" width="10" alt="" style="margin-right:8px">导出
      </v-contextmenu-item>
      <v-contextmenu-item
        v-if="contextmenuData && contextmenuData.suffix.includes('html')"
        v-clipboard:copy="invitationCode"
        v-clipboard:success="copy"
        v-clipboard:error="onError"
      >
        <img src="~@/assets/copyLink.png" width="10" alt="" style="margin-right:8px">复制链接
      </v-contextmenu-item>
      <v-contextmenu-item v-if="isEdit === 2" @click="applyDdit">
        <img src="~@/assets/apply.png" width="10" alt="" style="margin-right:8px">申请编辑权限
      </v-contextmenu-item>
      <v-contextmenu-item v-if="isEdit === 1" @click="cancleDdit">
        <img src="~@/assets/export.png" width="10" alt="" style="margin-right:8px">释放编辑权限
      </v-contextmenu-item>
    </v-contextmenu>

    <a id="download" href download/>
  </div>
</template>

<script>
  import draggable from 'vuedraggable'
  import folderTree from './folder'
  import cont from './cont'
  import fileShare from './fileShare'
  import {
    fileList,
    fileRename,
    mindMapRename,
    fileDelete,
    mindMapDelete,
    exportHtml,
    cancleDdit,
    applyDdit,
    fileSort
  } from '@/api/file'
  import { showContextmenu } from '@/utils/index'
  import { fileJudge1, mindMapJudge1 } from './judge'

  export default {
    name: 'Priject',
    components: { folderTree, cont, fileShare, draggable },
    data() {
      return {
        isShow: false,
        folderId: null,
        searchInput: '',
        fileList: [],
        fileListIsHide: true,
        contextmenuData: null,
        downloadName: '',
        fileShareData: {
          title: '',
          dialogFormVisible: false,
          fileid: '',
          userid: ''
        }
      }
    },
    computed: {
      authority() {
        return this.$store.state.index.authority
      },
      isEdit() {
        const realname = JSON.parse(sessionStorage.userInfo).realName
        console.log(realname)
        console.log(this.contextmenuData)
        return this.contextmenuData
          ? this.contextmenuData.suffix.includes('html')
            ? this.contextmenuData.editor === realname
              ? 1
              : 2
            : 3
          : ''
      },
      invitationCode() {
        return `${process.env.VUE_APP_BASE_API}/file/note/get?fileid=${this.contextmenuData.id}`
      }
    },
    created() {
    },
    methods: {
      selectedFolder(data) {
        this.folderId = data.id ? data.id : this.folderId
        fileList(this.folderId, 'id', this.searchInput)
          .then(result => {
            const { data } = result
            this.fileList = data
            this.fileListIsHide = false
            this.$store.commit('index/set_selectedFile', { suffix: '' })
            console.log(result)
          })
          .catch(err => {
            console.log(err)
          })
      },
      selected(item) {
        // if (item.suffix === 'docx' || item.suffix === 'doc' || item.suffix === 'xls' || item.suffix === 'xlsx' || item.suffix === 'pdf') {
        //   this.$confirm(
        //     '您可以选择将此文档作为笔记直接编辑（我们会为您保留原始文件），或者点击继续预览以Word格式打开预览?',
        //     '',
        //     {
        //       confirmButtonText: '作为笔记编辑',
        //       cancelButtonText: '继续预览',
        //       type: 'warning',
        //       center: true
        //     }
        //   )
        //     .then(() => {
        //       this.exportHtml(item.id)
        //     })
        //     .catch(() => {
        //       this.aaa(item)
        //     })
        // } else {
          this.aaa(item)
        // }
      },
      aaa(item) {
        this.$nextTick(() => {
          // console.log(this.fileList)
          this.fileList.fileInfos.filter(item => (item.isActive = false))
          item.isActive = true
          this.$store.commit('index/set_selectedFile', { suffix: '' })
          this.$nextTick(() => {
            this.$store.commit('index/set_selectedFile', item)
          })
          this.$forceUpdate()
        })
      },
      exportHtml(fileid) {
        exportHtml(fileid)
          .then(result => {
            this.selectedFolder({})
            console.log(result)
          })
          .catch(err => {
            console.log(err)
          })
      },
      contextmenu(event, item) {
        console.log(item)
        this.contextmenuData = item
        showContextmenu(this.$refs.contextmenu, event)
      },
      open() {
        if (this.authority.isUpdate === 0) {
          this.$message('无操作权限')
          return false
        }
        const title = '修改文件名'
        const inputValue = this.contextmenuData.name.replace(
          '.' + this.contextmenuData.suffix,
          ''
        )

        this.$prompt('', title, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue,
          closeOnClickModal: false,
          beforeClose: async(action, instance, done) => {
            if (action === 'confirm') {
              console.log(instance)
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '执行中...'
              this.instance = instance
              this.done = done

              const name = this.instance.inputValue
              if (this.contextmenuData.suffix === 'html') {
                const parentId = this.selectedNode ? this.selectedNode.id : 0
                const is = await fileJudge1(parentId, name)
                console.log(is)
                is ? this.fileRename() : this.instanceReset()
              } else {
                const parentId = this.selectedNode ? this.selectedNode.id : 0
                const is = await mindMapJudge1(parentId, name)
                console.log(is)
                is ? this.mindMapRename() : this.instanceReset()
              }
            } else {
              done()
            }
          }
        })
      },
      fileRename() {
        const name = this.instance.inputValue + '.' + this.contextmenuData.suffix
        const parentId = this.contextmenuData.parentId
        const folderId = this.contextmenuData.id
        fileRename(parentId, name, folderId)
          .then(result => {
            this.instance.confirmButtonLoading = false
            this.done()
            this.contextmenuData.name = name
          })
          .catch(err => {
            this.instanceReset()
            console.log(err)
          })
      },
      mindMapRename() {
        const name = this.instance.inputValue
        const parentId = this.contextmenuData.parentId
        const folderId = this.contextmenuData.id
        mindMapRename(parentId, name, folderId)
          .then(result => {
            this.instance.confirmButtonLoading = false
            this.done()
            this.contextmenuData.name = name
          })
          .catch(err => {
            this.instanceReset()
            console.log(err)
          })
      },
      deleteFile() {
        if (this.authority.isUpdate === 0) {
          this.$message('无操作权限')
          return false
        }
        // if (this.contextmenuData.suffix === 'json') {
        // this.mindMapDelete()
        // } else {
        this.fileDelete()
        // }
      },
      fileDelete() {
        const id = this.contextmenuData.id
        fileDelete(id)
          .then(result => {
            this.fileList.fileInfos.splice(
              this.fileList.fileInfos.findIndex(v => v.id === id),
              1
            )

            if (id === this.$store.state.index.selectedFile.id) {
              this.$store.commit('index/set_selectedFile', { suffix: '' })
            }
          })
          .catch(err => {
            console.log(err)
          })
      },
      mindMapDelete() {
        const id = this.contextmenuData.id
        mindMapDelete(id)
          .then(result => {
            this.fileList.fileInfos.splice(
              this.fileList.fileInfos.findIndex(v => v.id === id),
              1
            )
          })
          .catch(err => {
            console.log(err)
          })
      },
      share() {
        this.fileShareData = {
          title: '选择人员',
          dialogFormVisible: true,
          fileid: this.contextmenuData.id,
          userid: ''
        }
        this.$forceUpdate()
      },
      download() {
        const download = document.querySelector('#download')
        if (this.contextmenuData.suffix.includes('html')) {
          download.href =
            process.env.VUE_APP_BASE_API +
            '/file/export/word?fileid=' +
            this.contextmenuData.id
        } else {
          download.href =
            process.env.VUE_APP_BASE_API +
            '/file/download?id=' +
            this.contextmenuData.id
        }

        console.log(
          process.env.VUE_APP_BASE_API +
          '/file/export/word?fileid=' +
          this.contextmenuData.id
        )
        download.click()
      },
      applyDdit() {
        const fileid = this.contextmenuData.id
        applyDdit({ fileid })
          .then(result => {
            const { data } = result
            if (data) {
              this.contextmenuData.editor = JSON.parse(
                sessionStorage.userInfo
              ).realName
              console.log(result)
              this.$store.commit('index/set_selectedFile', { suffix: '' })

              this.$nextTick(() => {
                this.$store.commit('index/set_selectedFile', this.contextmenuData)
              })
            } else {
              this.$message(result.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      },
      cancleDdit() {
        const fileid = this.contextmenuData.id
        cancleDdit({ fileid })
          .then(result => {
            this.contextmenuData.editor = ''
            this.$store.commit('index/set_selectedFile', { suffix: '' })
            this.$nextTick(() => {
              this.$store.commit('index/set_selectedFile', this.contextmenuData)
            })
            console.log(result)
          })
          .catch(err => {
            console.log(err)
          })
      },
      colseDialog() {
        this.fileShareData.dialogFormVisible = false
      },
      copy(e) {
        this.$message('复制成功')
        console.log(e)
      },
      onError(e) {
        this.$message('复制失败')
        console.log(e)
      },
      instanceReset() {
        this.instance.confirmButtonLoading = false
        this.instance.confirmButtonText = '确定'
      },
      //拖动排序
      end(evt) {
        const parentArr = this.fileList.fileInfos
        if (parentArr !== null) {
          let beforeId = 0
          let endId = 0
          let currentId = parentArr[evt.newIndex].id
          let before = 0
          let end = 0
          const current = evt.newIndex
          if (current === 0) {
            before = -1
            end = current + 1
          } else if (current !== 0) {
            before = current - 1
            end = current + 1
          }
          if (current === parentArr.length - 1) {
            end = -1
          }
          beforeId = before === -1 ? 0 : parentArr[before].id
          endId = end === -1 ? 0 : parentArr[end].id
          console.log(before, current, end)
          fileSort(currentId, beforeId, endId)
            .then(result => {
              console.log(result)
            })
            .catch(err => {
              console.log(err)
            })
        }
      },
      getPositionById(arr, id) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].data.id === id) {
            return i
          }
        }
        return -1
      }
    }
  }
</script>

<style lang="scss" scoped>
  #priject {
    border-radius: 24px 0px 0 0px;

    .left {
      position: relative;

      .arrow {
        font-size: 30px;
        position: absolute;
        right: -30px;
        bottom: 30px;
        cursor: pointer;
        transform: rotate(180deg);
        z-index: 999;
      }
    }

    &.active {
      .left {
        .arrow {
          transform: rotate(0deg);
        }

        .catalog,
        .content {
          display: none;
        }
      }
    }

    .content {
      width: 257px;
      background: rgba(249, 249, 249, 1);
      flex-direction: column;
      border-right: 1px solid #eaeaea;

      .search {
        // width: 202px;
        height: 76px;
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
        padding: 18px 8px;
      }

      .list {
        flex: 1;

        dl {
          width: 232px;
          background-color: #fff;
          margin: 10px 13px 9px 12px;
          padding: 15px 13px;
          position: relative;
          border-radius: 4px;

          &:hover {
            cursor: pointer;
            background-color: rgba(44, 161, 213, 0.1);
          }

          img {
            width: 20px;
            position: absolute;
            right: 15px;
            bottom: 10px;
          }

          &.active {
            background-color: rgba(44, 161, 213, 0.05);

            dt {
              color: rgba(44, 161, 213, 1);
            }

            dd {
              color: #3ec5ef;
            }
          }

          dt {
            height: 21px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(113, 113, 113, 1);
            line-height: 22px;
            padding-right: 20px;
          }

          dd {
            height: 17px;
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(190, 190, 190, 1);
            line-height: 17px;
            padding-top: 4px;
            margin: 0;
          }
        }
      }
    }
  }
</style>

<style lang="scss">
  .search {
    .el-input__inner {
      border-radius: 30px;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }

    .el-input-group__append {
      border-radius: 30px;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
</style>
